﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="RelatedDocumentsService.cs" company="Microsoft">
//   Microsoft
// </copyright>
// <summary>
//   Provides access to Related Documents
// </summary>
// Copyright (c) Microsoft Corporation. All rights reserved.
// 
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, 
// EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES 
// OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
// ----------------------------------------------------------------------------------
// The example companies, organizations, products, domain names,
// e-mail addresses, logos, people, places, and events depicted
// herein are fictitious.  No association with any real company,
// organization, product, domain name, email address, logo, person,
// places, or events is intended or should be inferred.
// --------------------------------------------------------------------------------------------------------------------

namespace MySemanticSearch.Web.DataAccess
{
    using System;
    using System.Collections.Generic;
    using System.Data.SqlClient;
    using System.Globalization;
    using System.ServiceModel.DomainServices.Hosting;
    using System.ServiceModel.DomainServices.Server;
    using System.Web.Management;

    using MySemanticSearch.Web.Model;

    /// <summary>
    /// Provides access to Related Documents
    /// </summary>
    [EnableClientAccess]
    public class RelatedDocumentsService : DomainService
    {
        /// <summary>
        /// Maximum number of decimals for tags and documents' score
        /// </summary>
        private const int RoundScore = 5;

        /// <summary>
        /// Given a document this method queries the database for a list of related documents
        /// </summary>
        /// <param name="sqlInstance">
        /// The sql instance.
        /// </param>
        /// <param name="database">
        /// The database.
        /// </param>
        /// <param name="fileTable">
        /// The file table.
        /// </param>
        /// <param name="docId">
        /// The doc name.
        /// </param>
        /// <returns>
        /// A dictionary with doc names as keys and score as values
        /// </returns>
        public IList<Document> GetRelatedDocuments(string sqlInstance, string database, string fileTable, string docId)
        {
            var related = new List<Document>();

            if (string.IsNullOrEmpty(sqlInstance) || string.IsNullOrEmpty(database) || string.IsNullOrEmpty(fileTable) || string.IsNullOrEmpty(docId))
            {
                return related;
            }

            using (var connection = SqlServerManagement.ConnectServerInstance(sqlInstance, database).ConnectionContext.SqlConnectionObject)
            {
                var query = String.Format(CultureInfo.InvariantCulture, App_Data.SqlQueries.GetRelatedDocuments, fileTable, docId);
                using (var command = new SqlCommand(query))
                {
                    try
                    {
                        command.Connection = connection;
                        using (var reader = command.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                var document = new Document
                                {
                                    Created = reader.GetString(0),
                                    Modified = reader.GetString(1),
                                    Accessed = reader.GetString(2),
                                    Guid = reader.GetSqlGuid(3).ToString(),
                                    ReadOnly = reader.GetSqlBoolean(4).Value,
                                    Hidden = reader.GetSqlBoolean(5).Value,
                                    FileName = reader.GetString(6),
                                    FileType = reader.GetString(7),
                                    Score = Math.Round(reader.GetFloat(8), RoundScore)
                                };

                                related.Add(document);
                            }
                        }
                    }
                    catch
                    {
                        var errorInformation = String.Format(CultureInfo.CurrentCulture, App_Data.ExceptionMessages.FormatDatabase, database) + Environment.NewLine +
                            String.Format(CultureInfo.CurrentCulture, App_Data.ExceptionMessages.FormatFileTable, fileTable) + Environment.NewLine;
                        var errorMessage = App_Data.ExceptionMessages.GetDocumentTagsError;

                        throw new SqlExecutionException(errorMessage + Environment.NewLine + errorInformation);
                    }
                }
            }

            return related;
        }

        /// <summary>
        /// Overrides default OnError behaviour when an exception occurs
        /// </summary>
        /// <param name="errorInfo">
        /// The error info.
        /// </param>
        protected override void OnError(DomainServiceErrorInfo errorInfo)
        {
            if (errorInfo == null)
            {
                return;
            }

            var serviceException = errorInfo.Error;
            if (serviceException == null)
            {
                return;
            }

            throw new DomainException(serviceException.Message);
        }
    }
}
